import load
import load2
import numpy as np
import keras
import pickle
import LossHistory

keras.initializers.RandomNormal(mean=0.0, stddev=0.05, seed=None)

class dingjiaModel:
    def __init__(self,model_file=None):
        model = keras.Sequential()
        model.add(keras.layers.Dense(5, input_shape=(8,), activation='relu'))
        model.add(keras.layers.Dense(3, activation='sigmoid'))
        model.add(keras.layers.Dense(2, activation='sigmoid'))
        opt=keras.optimizers.adam()
        model.compile(optimizer=opt, loss=keras.losses.mse)
        self.model = model

        if model_file:
            self.model = pickle.load(open(model_file, 'rb'))
            # self.model.set_weights(net_params)

    def train(self, allX, allY):
        history = LossHistory.LossHistory()
        self.model.fit(allX, allY, epochs=4000, batch_size=230, callbacks=[history])
        return history

    def predict(self, allX):
        npresult=self.model.predict(allX)

        def toBin(x):
            if x > 0.5:
                return 1
            else:
                return 0

        result=[]
        for n1, n2 in npresult:
            result.append([toBin(n1),toBin(n2)])
        return result


    def save(self,name):
        pickle.dump(self.model, open(name+'.pkl', 'wb'), protocol=2)

    def test(self,allX,allY):
        allY_=self.predict(allX)
        rightNum=0
        rightGroupNum=0
        for i in range(len(allY_)):
            y1_,y2_=allY_[i]
            y1,y2=allY[i]
            if y1==y1_:
                rightNum+=1
            if y2==y2_:
                rightNum+=1
            if y1==y1_ and y2==y2_:
                rightGroupNum+=1

        return rightGroupNum,len(allY_),rightNum,len(allY_)*2

def readX(isT1=True):
    allX = []
    for i in range(1, 7):  # 6个公司
        D2StartSub = load2.getStartSub(i)
        for j in range(39):  # 39个渠道
            x = []
            for d in range(8):  # 8个数据
                if isT1:
                    x.append(float(load2.getCellT1(D2StartSub + j, load2.d1 + d)))
                else:
                    x.append(float(load2.getCellT2(D2StartSub + j, load2.d1 + d)))
            allX.append(x)
    return allX

# 读入二进制码
allY=[]
for i in range(1,7):
    T2StartSub=load.getT2StartSub(i)
    for j in range(39): # 39个渠道
        y=[]
        for d in range(2): # 2个二进制代码
            y.append(float(load.getCellT2(j,T2StartSub+d)))
        allY.append(y)
print(allY)
allY=np.array(allY)

if __name__=='__main__':
    # 读入13-16数据
    allX=readX()
    allX=np.array(allX)

    model=dingjiaModel()
    model.train(allX,allY).loss_plot('epoch')
    model.save('model')
